/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "i2c.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"
#include "AHT20-21_DEMO_V1_3.h"
#include "stdio.h"
#include "u8g2.h"
#include "test.h"
#include "stm32u8g2.h"
#include "stm32f1xx_hal.h"
#include "wifi.h"
#include "SR04.h"
#include <string.h>
#include <stdio.h>


/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
uint32_t CT_data[2]={0,0};
uint8_t temperature;
uint8_t humidity;
uint8_t LED_Switch=0;
extern float distant;
float voltage;
char Onedate[20];
char Twodate[20];
int h1;
int t1;
u8g2_t u8g2;
char udp_cmd[64];
char tx_buffer[50];
/* 用户自定义接收缓冲区 */
#define RX_BUF_SIZE 128  // 根据实际需求调整大小

// 接收控制变量（需要volatile保证多线程可见性）
volatile uint8_t rx_flag = 0;    // 接收完成标志
char rx_buffer[RX_BUF_SIZE];      // 接收缓冲区
uint8_t rx_data;                 // 单字节接收缓存
uint16_t rx_index = 0;           // 缓冲区索引

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
    if (huart == &huart2) {
        static uint8_t index = 0;
        if (rx_data == '\n') { // 检测结束符
            rx_flag = 1;
            index = 0;
        } else {
            rx_buffer[index++] = rx_data;
        }
        HAL_UART_Receive_IT(&huart2, &rx_data, 1);
    }
}

void Process_Received_Data(char *data) {
    char *colon_ptr = strchr(data, ':');

    if (colon_ptr != NULL) {
        int val = atoi(colon_ptr + 1); 
        LED_Switch = val;  
    }
}

void LigtChange(){
    HAL_ADC_Start(&hadc1);

    //等待转换完成
    HAL_ADC_PollForConversion(&hadc1,HAL_MAX_DELAY);

    //获取结果
    uint32_t dr=HAL_ADC_GetValue(&hadc1);

    //把结果转换为电压
    voltage=dr*(3.3f-0.0f)/4095.0f;
    printf("Voltage: %.2f V\n",voltage);

    HAL_Delay(1000);
    SR04_GetData();
 
  	printf("LED_Switch:%d\r\n",LED_Switch);
    if(LED_Switch==4){
        if(distant<80)
        {
            __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_4, 400);
            //然后根据光线强度决定的强弱决定灯光强度
            if(voltage<=1)
            {
                __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_4, 100);
            }
            else if(voltage>1&&voltage<=2)
            {
                __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_4, 400);
            }
            else
                __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_4, 900);
        }
    }
    else{
        if(LED_Switch==1){
					__HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_4, 100);
				}
        else if(LED_Switch==2){
					__HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_4, 400);
				}
        else if(LED_Switch==3){
					__HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_4, 900);
				}
				else if(LED_Switch==0){
				  __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_4, 0);
				}
    }
}

void AHT20WROK(){
    AHT20_Read_CTdata_crc(CT_data);
    h1 = CT_data[0]*1000/1024/1024;
    t1 = CT_data[1]*2000/1024/1024-500;
    temperature=t1/10;
    humidity=h1/10;
    printf("湿度:%d温度:%d\r\n",humidity,temperature);
}

void OLEDWORK(){
    sprintf(Onedate,"Temperature:%d%d.%d",t1/100,(t1/10)%10,t1%10);
    sprintf(Twodate,"Humidity:%d%d.%d",h1/100,(h1/10)%10,h1%10);
    u8g2_FirstPage(&u8g2);
    do
    {
        draw(&u8g2);
        u8g2_ClearBuffer(&u8g2);
        u8g2_DrawStr(&u8g2,3, 30, Onedate);
        u8g2_DrawStr(&u8g2,3, 40, Twodate);
    } while (u8g2_NextPage(&u8g2));
}

void ESP8266WORKSEND(){
    snprintf(udp_cmd, sizeof(udp_cmd), "AT+CIPSTART=\"UDP\",\"192.168.43.170\",8080,1111,0\r\n");
    HAL_UART_Transmit(&huart2, (uint8_t*)udp_cmd, strlen(udp_cmd), 2000);
    sprintf(tx_buffer, "%d,%d\r\n", temperature, humidity);
	  HAL_Delay(1000);
    ESP8266_SendUDP(tx_buffer);
}

void ESP8266WORKRECIVE(){
    if (rx_flag) {
        Process_Received_Data(rx_buffer);
        // 清空标志和缓冲区
        rx_flag = 0;
        memset(rx_buffer, 0, sizeof(rx_buffer));
    }
    printf("\r\n");
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

    /* USER CODE BEGIN 1 */

    /* USER CODE END 1 */

    /* MCU Configuration--------------------------------------------------------*/

    /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
    HAL_Init();

    /* USER CODE BEGIN Init */

    /* USER CODE END Init */

    /* Configure the system clock */
    SystemClock_Config();

    /* USER CODE BEGIN SysInit */

    /* USER CODE END SysInit */

    /* Initialize all configured peripherals */
    MX_GPIO_Init();
    MX_I2C1_Init();
    MX_I2C2_Init();
    MX_USART1_UART_Init();
    MX_USART2_UART_Init();
    MX_TIM3_Init();
    MX_ADC1_Init();
    MX_TIM1_Init();
    MX_TIM2_Init();
    /* USER CODE BEGIN 2 */

    __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_4, 0);
    HAL_TIM_PWM_Start(&htim1,TIM_CHANNEL_4); //启动正常输出

    wifi_init();
    printf("WIFI启动\r\n");
    HAL_Delay(500);
    AHT20_Init();
    printf("AHT20启动\r\n");
    HAL_Delay(500);
    atk_mw8266d_uart_rx_restart();
    HAL_Delay(500);
    u8g2Init(&u8g2);
    printf("OLED启动\r\n");
    HAL_UART_Receive_IT(&huart2, &rx_data, 1); // 启动首次接收

    /* USER CODE END 2 */

    /* Infinite loop */
    /* USER CODE BEGIN WHILE */
    while (1)
    {
        /* USER CODE END WHILE */
        //启动常规序列
        AHT20WROK();
        HAL_Delay(500);
        OLEDWORK();
        HAL_Delay(500);
        ESP8266WORKSEND();
        HAL_Delay(500);
        LigtChange();
        HAL_Delay(500);
        ESP8266WORKRECIVE();

    }
    /* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */


/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
  RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL2;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
  {
    Error_Handler();
  }
  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC;
  PeriphClkInit.AdcClockSelection = RCC_ADCPCLK2_DIV2;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
